/*
 * Copyright 2005-2013 shopxx.net. All rights reserved.
 * Support: http://www.shopxx.net
 * License: http://www.shopxx.net/license
 */
package com.xiaorong.interceptor;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.xiaorong.Principal;
import com.xiaorong.dao.AdminDao;
import com.xiaorong.dao.RoleDao;
import com.xiaorong.entity.Admin;
import com.xiaorong.entity.LogConfig;
import com.xiaorong.entity.Role;
import com.xiaorong.util.LogConfigUtils;

/**
 * 做个简单的权限控制
 * @author LV_FQ
 *
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

	private static AntPathMatcher antPathMatcher = new AntPathMatcher();
	
	private static String NO_AUTH_PAHT = "/common/noAuth.do";

	@Resource
	private AdminDao adminDao;
	@Resource
	private RoleDao roleDao;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		List<LogConfig> logConfigs = LogConfigUtils.getAll();
		if (logConfigs != null) {
			String path = request.getServletPath();
			for (LogConfig logConfig : logConfigs) {
				if (antPathMatcher.match(logConfig.getUrlPattern(), path)) {
					
					Principal principal = (Principal) request.getSession().getAttribute("adminUsername");
					
					Admin admin = adminDao.find(principal.getId());
					
					//把权限保存到session中
					Set<String> authorities = new HashSet<String>();
					for(Role role : admin.getRoles()){
						authorities.addAll(role.getAuthorities());
					}
					
					if(authorities.contains(logConfig.getAuth())){
						return true;
					}else{
						String requestType = request.getHeader("X-Requested-With");
						if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
							//如果是异步请求
							response.setHeader("noAuth", "true");
							return false;
						} else {
							response.sendRedirect(request.getContextPath() + NO_AUTH_PAHT);
							return false;
						}
					}
				}
			}
		}
		
		return super.preHandle(request, response, handler);
	}
}